package com.pescamillam.consultadeprecios;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.RemoteException;
import android.util.Log;

public class AlmacenamientoProductos {
	
	private BaseDeDatosProductos baseDeDatos;
	private static String nombreTabla = "PRODUCTOS";
	
	static class BaseDeDatosProductos extends SQLiteOpenHelper {

		public BaseDeDatosProductos(Context context) {
			super(context, "BaseDeDatosProductos", null, 1);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			StringBuilder crearTablaQuery = new StringBuilder();
			crearTablaQuery.append("create table if not exists " + nombreTabla + " (");
			crearTablaQuery.append(Constants.Database.Columns.ID + " integer primary key autoincrement ");
			
			String [] names = Constants.Database.COLUMN_NAMES;
			String [] types = Constants.Database.COLUMN_TYPES;
			
			for (int i = 1; i < names.length; ++i) {
				crearTablaQuery.append(", " + names[i] + " " +types[i]);
			}
			
			crearTablaQuery.append(");");
			
			Log.d("AlmacenamientoProductos", "onCreate() called: " + crearTablaQuery.toString());
			
			try {
				db.execSQL(crearTablaQuery.toString());
			}
			catch (SQLException e) {
				Log.e("MoocResolver", e.getMessage());
			}
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			
		}
		
	}
	
	public AlmacenamientoProductos(Context context) {
		baseDeDatos = new BaseDeDatosProductos(context);
	}
	
	/**
	 * When the user of this class is done with it, make sure to close the database.
	 */
	@Override
	public void finalize() {
		if (baseDeDatos != null)
			baseDeDatos.close();
	}
	
	public int borrarProductos(final String seleccion,
			final String[] argumentos) throws RemoteException {
		SQLiteDatabase db = baseDeDatos.getWritableDatabase();
		int res = db.delete(nombreTabla, seleccion, argumentos);
		return res;
	}
	
	public long insertarProducto(final ProductData storyObject) throws RemoteException {
		ContentValues tempCV = storyObject.getCV();
		tempCV.remove(Constants.Database.Columns.ID);
		SQLiteDatabase db = baseDeDatos.getWritableDatabase();
		long res = db.insert(nombreTabla, null, tempCV);
		db.close();
		return res;
	}
	
	public ArrayList<ProductData> obtenerProductos (final String[] projection,
			final String selection, final String[] selectionArgs,
			final String sortOrder) {
		// query the database
		SQLiteDatabase db = baseDeDatos.getReadableDatabase();
		Cursor result = db.query(nombreTabla, projection, selection,
				selectionArgs, null, null, sortOrder);
		// make return object
		ArrayList<ProductData> rValue = new ArrayList<ProductData>();
		// convert cursor to reutrn object
		rValue.addAll(StoryCreator.getStoryDataArrayListFromCursor(result));
		result.close();
		
		//close the database
		db.close();
		
		// return 'return object'
		return rValue;
	}
	
	/**
	 * Update the specified StoryData with new values.
	 * 
	 * @param values
	 * @param selection
	 * @param selectionArgs
	 * @return number of rows changed
	 * @throws RemoteException
	 */
	public int actualizarProducto(final ProductData values, final String selection,
			final String[] selectionArgs) throws RemoteException {
		
		SQLiteDatabase db = baseDeDatos.getWritableDatabase();
		int res = db.update(nombreTabla, values.getCV(), selection, selectionArgs);
		db.close();
		return res;
	}
	
	/**
	 * Get all the StoryData objects current stored in the Content Provider
	 * 
	 * @return an ArrayList containing all the StoryData objects
	 * @throws RemoteException
	 */
	public ArrayList<ProductData> getAllStoryData() throws RemoteException {
		return obtenerProductos(null, null, null, null);
	}
	
	/**
	 * Get a StoryData from the data stored at the given rowID
	 * 
	 * @param rowID
	 * @return StoryData at the given rowID
	 * @throws RemoteException
	 */
	public ProductData getStoryDataViaRowID(final long rowID)
			throws RemoteException {
		String[] selectionArgs = { String.valueOf(rowID) };
		ArrayList<ProductData> results = obtenerProductos(null,
				Constants.Database.Columns.ID + "= ?", selectionArgs, null);
		if (results.size() > 0) {
			return results.get(0);
		} else {
			return null;
		}
	}
	
	/**
	 * Get a StoryData from the data stored at the given rowID
	 * 
	 * @param rowID
	 * @return StoryData at the given rowID
	 * @throws RemoteException
	 */
	public ProductData getProductViaCode (final String code)
			throws RemoteException {
		String[] selectionArgs = { String.valueOf(code) };
		ArrayList<ProductData> results = obtenerProductos(null,
				Constants.Database.Columns.CODE + "= ?", selectionArgs, null);
		if (results.size() > 0) {
			return results.get(0);
		} else {
			return null;
		}
	}
	/**
	 * Delete All rows, from AllStory table, that have the given rowID. (Should
	 * only be 1 row, but Content Providers/SQLite3 deletes all rows with
	 * provided rowID)
	 * 
	 * @param rowID
	 * @return number of rows deleted
	 * @throws RemoteException
	 */
	public int deleteAllStoryWithRowID(long rowID) throws RemoteException {
		String[] args = { String.valueOf(rowID) };
		return borrarProductos(Constants.Database.Columns.ID + " = ? ", args);
	}
	
	/**
	 * Updates all StoryData stored with the provided StoryData's 'KEY_ID'
	 * (should only be 1 row of data in the content provider, but content
	 * provider implementation will update EVERY row that matches.)
	 * 
	 * @param data
	 * @return number of rows altered
	 * @throws RemoteException
	 */
	public int actualizarProducto(ProductData data) throws RemoteException {
		String selection = Constants.Database.Columns.ID +" = ?";
		String[] selectionArgs = { String.valueOf(data.KEY_ID) };
		return actualizarProducto(data, selection, selectionArgs);
	}
}
